﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

namespace Core
{
    //TODO 
    //1. 适配持久化路径
    //2. 使用Stream方式保存、减少写入消耗
    //3. 设置最大保存日志个数，删除最老的

    public class LogSystem : EntitySystem, IAwake
    {
        private IAssetHelper assetHelper;
        private string savePath;

        public void Awake()
        {
            assetHelper = GetHelper<IAssetHelper>();

            var now = DateTime.Now;
            var nowStr = $"{now.Year}_{now.Month}_{now.Day}_{now.Hour}_{now.Minute}";
            savePath = $"{Application.dataPath}/../GameLogs/{nowStr}.txt";
            assetHelper.SaveString(savePath, "");

            Subscribe<SaveLog>(SaveLog);
        }

        private void SaveLog(ref SaveLog data)
        {
            var stackTrace = "";
            if (data.level == LogLevel.Error)
                stackTrace = $"{data.stackTrace}\n";

            var now = DateTime.Now.ToString("T");
            var log = $"[{data.level}]-[{now:HH:mm:ss}]\n{data.condition}\n{stackTrace}";
            assetHelper.AppendString(savePath, log);
        }
    }
}
